Vue.component('addForm', {
    template: `<el-dialog title="添加成员" :visible.sync="visibleDialog">
    <el-form ref="contract" :model="addForm" :rules="addRules" :inline-message="true">
        <el-descriptions :column="1" border size="small">
            <el-descriptions-item label="钉钉用户ID">
                <el-form-item prop="User_ID">
                    <el-input v-model.trim="addForm.User_ID" placeholder="请输入钉钉用户ID"></el-input>
                </el-form-item>
            </el-descriptions-item>
            <el-descriptions-item label="用户昵称">
                <el-form-item prop="User_Name">
                    <el-input v-model.trim="addForm.User_Name" placeholder="请输入用户昵称"></el-input>
                </el-form-item>
            </el-descriptions-item>
        </el-descriptions>
    </el-form>
    <div slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:visible',false)">取 消</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm('contract')">确 定</el-button>
    </div></el-dialog>`,
    props: ['visible'],
    data() {
        return {
            visibleDialog: false,
            addForm: {
                User_ID: '',
                User_Name: '',
                Enterprise_Info_SerialNumber: $.cookie('enterprise')
            },
            addRules: {
                User_ID: [{ required: true, message: '请输入钉钉用户ID', trigger: 'blur' }],
                User_Name: [{ required: true, message: '请输入用户昵称', trigger: 'blur' }]
            },
            loading: false,
        }
    },
    watch: {
        visible() {
            this.visibleDialog = this.visible
        },
        visibleDialog(val) {
            this.$emit('update:visible', val)
        }
    },
    methods: {
        submitForm(formName) {
            let that = this
            this.$refs[formName].validate((valid) => {
                if (valid) {
                    that.loading = true
                    $.ajax({
                        url: DomainName + '/DingTalkUserIdsAdd?token=' + $.cookie('token'),
                        type: 'POST',
                        data: {
                            Data: JSON.stringify({
                                dingtalk_userids_info: [that.addForm]
                            }),
                        },
                        success: function (res) {
                            if (res.Status === 'success') {
                                that.$message.success("提交成功")
                                that.visibleDialog = false;
                                that.$emit('success', true)
                            } else {
                                that.$message.error("提交失败，该钉钉用户ID已被录入")
                            }
                        },
                        error: function () {
                            that.$message.error("操作失败，请稍后再试")
                        },
                        complete: function (XMLHttpRequest) {
                            that.loading = false
                            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                                window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                            }
                        }
                    })
                } else {
                    return false;
                }
            });
        }
    },
})
Vue.component('batchAddForm', {
    template: `<el-dialog title="批量导入钉钉成员" :visible.sync="visibleDialog">
    <div style="height: 80px;">
        <el-upload ref="upload" class="upload-demo" accept=".xlsx" :limit="1" multiple drag action=""
            :file-list="fileList" :on-change="handleChange" :auto-upload="false">
            <i class="el-icon-upload"></i>
            <div class="el-upload__text">
                将文件拖到此处，或<em>点击上传</em><br>
            </div>
        </el-upload>
    </div>
    <el-table :data="tableData.slice((form.page-1)*form.limit,form.page*form.limit)" stripe border style="width: 100%" height="300px">
        <el-table-column align="center" label="序号" width="50" type="index"></el-table-column>
        <el-table-column align="center" prop="User_ID" label="钉钉用户ID">
            <template v-slot="{row}">
                <el-input v-if="row.isEdit" v-model="row.User_ID"></el-input>
                <span v-else>{{row.User_ID}}</span>
            </template>
        </el-table-column>
        <el-table-column align="center" prop="User_Name" label="用户昵称">
            <template v-slot="{row}">
                <el-input v-if="row.isEdit" v-model="row.User_Name"></el-input>
                <span v-else>{{row.User_Name}}</span>
            </template>
        </el-table-column>
        <el-table-column align="center" label="操作" width="180">
            <template v-slot="{row,$index}">
                <el-button size="small" :type="row.isEdit?'success':'primary'" @click="handleEdit(row)">
                    {{row.isEdit?'保存':'修改'}}
                </el-button>
                <el-button size="small" type="danger" @click="handleRemove($index)">删除</el-button>
            </template>
        </el-table-column>
    </el-table>
    <el-pagination style="margin-top: 5px;" background @size-change="handleSizeChange" @current-change="handleCurrentChange"
        :current-page="form.page" :page-sizes="[10 ,100, 200, 300, 400]" :page-size="form.limit"
        layout="total, sizes, prev, pager, next, jumper" :total="tableData.length">
    </el-pagination>
    <div slot="footer" class="dialog-footer">
        <el-button @click="$emit('update:visible',false)">取 消</el-button>
        <el-button type="success" @click="download">下载模板</el-button>
        <el-button :loading="loading" type="primary" @click="submitForm">确 定</el-button>
    </div></el-dialog>`,
    props: ['visible'],
    data() {
        return {
            visibleDialog: false,
            form: {
                page: 1,
                limit: 10,
            },
            tableData: [],
            fileList: [],
            loading: false,
        }
    },
    watch: {
        visible() {
            console.log(this.visible);
            this.visibleDialog = this.visible
        },
        visibleDialog(val) {
            this.$emit('update:visible', val)
        }
    },
    methods: {
        handleChange({ raw }) {
            let that = this;
            var reader = new FileReader();
            reader.readAsBinaryString(raw);
            reader.onload = function (e) {
                var data = e.target.result;
                var wb = XLSX.read(data, {
                    type: 'binary' //以二进制的方式读取
                });
                var sheet = wb.Sheets[wb.SheetNames[0]];//sheet0代表excel表格中的第一页
                var json = XLSX.utils.sheet_to_json(sheet);//利用接口实现转换。
                json.forEach(item => {
                    if (!that.tableData.some(i => i.User_ID == item['ID'])) {
                        that.tableData.push({
                            User_ID: item['ID'],
                            User_Name: item['用户昵称'],
                            isEdit: false,
                            Enterprise_Info_SerialNumber: $.cookie('enterprise')
                        })
                    }
                })
                that.$message.success("导入成功，已过滤掉重复ID");
            }
        },
        handleSizeChange(val) {
            this.form.page = 1;
            this.form.limit = val;
        },
        handleCurrentChange(val) {
            this.form.page = val;
        },
        handleEdit(row) {//修改当前行
            row.isEdit = !row.isEdit
        },
        handleRemove(index) {//移除当前行
            this.$confirm('是否要删除此行?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                this.tableData = this.tableData.filter((i, id) => id != index)
            }).catch(() => { });
        },
        download() {//下载模板
            window.location.href = './钉钉用户信息导入模板.xlsx'
        },
        submitForm(formName) {
            let that = this
            that.loading = true
            $.ajax({
                url: DomainName + '/DingTalkUserIdsAdd?token=' + $.cookie('token'),
                type: 'POST',
                data: {
                    Data: JSON.stringify({
                        dingtalk_userids_info: that.tableData
                    }),
                },
                success: function (res) {
                    if (res.Status === 'success') {
                        that.$message.success("提交成功")
                        that.visibleDialog = false;
                        that.$emit('success', true)
                    } else {
                        that.$message.error("提交失败，请稍后再试")
                    }
                },
                error: function () {
                    that.$message.error("操作失败，请稍后再试")
                },
                complete: function (XMLHttpRequest) {
                    that.loading = false
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                }
            })
        }
    },
})
new Vue({
    el: '#app',
    data() {
        return {
            form: {
                Data: 'dingtalk_userids_info',
                Primary_Key: '',
                Primary_Key_Name: 'User_Name',
                isVague: true,
                page: 1,			//页数
                limit: 10,			//每页数据条数
            },
            total: 0,
            tableData: [],		//表格数据
            dialogAdd: false,//添加成员
            dialogBatchAdd: false,// 批量添加
            multipleSelection: [],//选中的数据
            loading: false,
        }
    },
    mounted() {
        this.getList(this.form)
    },
    methods: {
        onSerach() {//查询方法
            this.form.page = 1;
            this.getList(this.form)
        },
        batchAdd() {//导入
            this.dialogBatchAdd = true;
        },
        batchRemove() {//批量移除
            const that = this;
            if (this.multipleSelection.length > 0) {
                this.$confirm('确认，是否要删除已选中的数据?', '提示', {
                    confirmButtonText: '确定',
                    cancelButtonText: '取消',
                    type: 'warning',
                }).then(() => {
                    this.loading = true;
                    this.multipleSelection.forEach(item => {
                        item.Row_Status = '1'
                    })
                    $.ajax({
                        url: `${DomainName}/getEditAction?token=${$.cookie('token')}`,
                        type: 'POST',
                        data: {
                            Data: JSON.stringify({ Modify: { dingtalk_userids_info: this.multipleSelection } }),
                            Operation_Name: '批量删除钉钉用户成员信息'
                        },
                        success: function (res) {
                            if (res.Status === 'success') {
                                that.$message.success("删除成功")
                                that.getList(that.form);
                            } else {
                                that.$message.error("删除失败，请稍后再试")
                            }
                        },
                        error: function () {
                            that.$message.error("操作失败，请稍后再试")
                        },
                        complete: function (XMLHttpRequest) {
                            that.loading = false;
                            if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                                window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                            }
                        }
                    })
                }).catch(() => { });
            } else {
                this.$message({
                    message: '请选择你要的记录',
                    type: 'warning'
                });
            }
        },
        handleSizeChange(val) {//改变当前一次性查询条数回调
            this.form.page = 1;
            this.form.limit = val;
            this.getList(this.form)
        },
        handleCurrentChange(val) {//改变当前查询页回调
            this.form.page = val;
            this.getList(this.form)
        },
        handleSelectionChange(val) {//多选中
            this.multipleSelection = val;
        },
        addSuccess(is) {//添加组件成功回调
            if (is) {
                this.getList(this.form)
            }
        },
        getList(data) {//分页查询
            let _this = this
            $.ajax({
                type: 'POST',
                url: `${DomainName}/getTableInquiryAction?token=${$.cookie('token')}`,
                data,
                complete: function (XMLHttpRequest) {
                    if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                        window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                    }
                },
                success: function (Result) {
                    if (Result.Status == 'success') {
                        Result.tableData.forEach(item => {
                            item.isEdit = false;
                            item.loading = false;
                            item.isError = false;
                        })
                        _this.tableData = Result.tableData
                        _this.total = parseInt(Result.limit)
                    }
                },
                dataType: "json"
            });
        },
        Add() {//添加
            this.dialogAdd = true
        },
        Edit(row) {//修改
            if (row.isEdit) {
                const that = this;
                if (!row.User_ID) {
                    that.$message.error(`钉钉用户ID不能为空`)
                    return
                }
                if (!row.User_Name) {
                    that.$message.error(`用户昵称不能为空`)
                    return
                }
                row.loading = true
                $.ajax({
                    url: `${DomainName}/getEditAction?token=${$.cookie('token')}`,
                    type: 'POST',
                    data: {
                        Data: JSON.stringify({ Modify: { dingtalk_userids_info: [row] } }),
                        Operation_Name: '修改钉钉用户成员信息'
                    },
                    success: function (res) {
                        if (res.Status === 'success') {
                            that.$message.success("修改成功")
                            that.getList(that.form);
                        } else {
                            that.$message.error("提交失败，请稍后再试")
                        }
                    },
                    error: function () {
                        that.$message.error("操作失败，请稍后再试")
                    },
                    complete: function (XMLHttpRequest) {
                        row.loading = false
                        row.isEdit = false;
                        if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                        }
                    }
                })
            } else {
                row.isEdit = true;
            }
        },
        Delete(row) {//删除
            const that = this
            this.$confirm('警告！此操作将删除该用户, 是否继续?', '提示', {
                confirmButtonText: '确定',
                cancelButtonText: '取消',
                type: 'warning',
            }).then(() => {
                $.ajax({
                    url: DomainName + '/DeleteAction?token=' + $.cookie('token'),
                    type: 'POST',
                    data: {
                        TableName: 'dingtalk_userids_info',
                        Primary_Key: row.User_ID,
                        Primary_Key_Name: 'User_ID',
                        Operation_Name: '删除用户信息'
                    },
                    success: function (res) {
                        if (res.Status == 'success') {
                            that.getList(that.form);
                            that.$message({ type: 'success', message: '删除成功!' });
                        }
                    },
                    complete: function (XMLHttpRequest) {
                        if (XMLHttpRequest.getResponseHeader("REDIRECT") == "REDIRECT") {
                            window.parent.document.location.href = absolutepath() + XMLHttpRequest.getResponseHeader("CONTENTPATH");
                        }
                    }
                })
            }).catch(() => { });
        }
    },
})